<?php
/**
 * Created by PhpStorm.
 * User: 六花
 * Date: 2019/4/27
 * Time: 17:20
 */

namespace Api\Controller;

use Think\Controller;
use Think\Exception;


class GoodsController extends Controller {

    public  function  __construct()
    {

    }

//    public function addGoods(){
//        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('"[','[',$GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace(']"',']',$GLOBALS['HTTP_RAW_POST_DATA']);
//        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
//        if(!$_POST || !is_array($_POST)){
//            $return_array = array(
//                'MessageCode' => 2,
//                'Message' => '参数错误'
//            );
//            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
//            exit;
//        }
//
//        $goods_model = M('goods');
//        $spec_model = M('goods_spec');
//        $brand_model = M('brand');
//        $country_model = M('country_info');
//        $unit_model = M('unit');
//        $wrap_model = M('wrap');
//        $tax_model = M('my_tax');
//        $stock_model = M('storestock');
//        $store_model = M('store');
//
//        if(!$_POST['ProductItems'] || !is_array($_POST['ProductItems'])){
//            $return_array = array(
//                'Sku' => '',
//                'Field' => 'Manufacturer',
//                'Msg' => '参数错误',
//                "Result" => 0
//            );
//            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
//            exit;
//        }
//        $send_array = array();
//        $pic_array = array();
//
//        foreach ($_POST['ProductItems'] as $key => $value){
//            //查重
//            $res_sku = $goods_model -> where(array('sku'=>$value['Sku']))->find();
//            if(!$res_sku){
//
//
//                if($value['SpecItems'] && is_array($value['SpecItems'])){
//                    //logo
//                    $temp_logo = trim($value['Manufacturer']);
//                    if($temp_logo){
//                        $res_logo = $brand_model -> where(array('brand_name'=>$temp_logo)) -> find();
//                        if(!$res_logo){
//                            $logo_add = $brand_model -> add(array('brand_name'=>$temp_logo));
//                            if(!$logo_add){
//                                $send_array[] = array(
//                                    'Sku' => $value['SwiftNumber'],
//                                    'Field' => 'Manufacturer',
//                                    'Msg' => '品牌添加失败',
//                                    "Result" => 0
//                                );
//                                continue;
//                            }
//                        }
//                    }
//
//                    //出产地
//                    $temp_country = $country_model -> where(array('country_code'=>$value['CountryId'])) ->find();
//                    if(!$temp_country){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'CountryId',
//                            'Msg' => '出产地查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//                    //单位
//                    $temp_unit = $unit_model -> where(array('unit_code'=>$value['UnitId'])) ->find();
//                    if(!$temp_unit){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'CountryId',
//                            'Msg' => '出产地查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//                    //包装
//
//                    $temp_wrap = $wrap_model -> where(array('wrap_code'=>$value['WrapId'])) ->find();
//
//                    if(!$temp_wrap){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'WrapId',
//                            'Msg' => '包装查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//                    //税率
//                    $consolidated_tax = get_consolidated_tax($value['ConsumptionTaxRate'],$value['VATRate']);
//                    $r['add_tax'] = $value['VATRate'];
//                    $r['consumption_tax'] = $value['ConsumptionTaxRate'];
//                    $temp_tax = $tax_model -> where($r) ->find();
//
//                    if(!$temp_tax){
//                        $rx['add_tax'] = $value['VATRate'];
//                        $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
//                        $rx['consolidated_tax'] = $value['consolidated_tax'];
//                        $rx['tax_name'] = '消费税为'.$value['ConsumptionTaxRate'].'的商品';
//                        $rx['consolidated_tax'] = $consolidated_tax;
//                        $add_tax = $tax_model -> add($rx);
//                        if(!$add_tax){
//                            $send_array[] = array(
//                                'Sku' => $value['SwiftNumber'],
//                                'Field' => 'ConsumptionTaxRate',
//                                'Msg' => '税率查询失败',
//                                "Result" => 0
//                            );
//                            continue;
//                        }
//                        $tax_id = $add_tax;
//                    }else{
//                        $tax_id = $temp_tax['tax_id'];
//                        $consolidated_tax = $temp_tax['consolidated_tax'];
//                    }
//                    //店铺
//                    $resStore = $store_model -> where(array('store_id'=>$value['StoreId'])) -> find();
//                    if(!$resStore){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                                'Field' => 'StoreId',
//                            'Msg' => '店铺查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//
//                    $pic = arraySort($_POST['ProductImgs'][$key]['SpecItems'], 'order', SORT_ASC);
//                    //分类
//                    $res_cate = M('gcategory')->where(array('cate_id'=>$value['CategoryId']))->find();
//                    if(!$res_cate){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '查询商品分类失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//                    $cate_name = $res_cate['cate_name'];
//                    $temp_cate = $res_cate;
//                    while ($temp_cate['parent_id'] != 0){
//                        $temp_cate = M('gcategory')->where(array('cate_id'=>$temp_cate['parent_id']))->find();
//                        $cate_name = $temp_cate['cate_name'] . ' ' . $cate_name;
//                    }
//
//                    $goods_array = array(
//                        'sku' => $value['Sku'],
//                        'cate_id' => $value['CategoryId'],
//                        'cate_name' => $cate_name,
//                        'goods_name' => $value['Name'],
//                        'description' => '<p></p>',
//                        'store_id' => $value['StoreId'],
//                        'price' => $value['Price'],
//                        'quantity' => $value['StockQuantity'],
//                        'market_price' => $value['OldPrice'],
//                        'brand' => $temp_logo,
//                        'if_show' => $value['Published'],
//                        'add_time' => $value['CreatedTimeStamp'],
//                        'last_update' => $value['UpdateTimeStamp'],
//                        //临时图 需要改
//                        'default_image' => $value['DefaultImg'],
//                        'country_id' => $temp_country['id'],
//                        'unit_id' => $temp_unit['id'],
//                        'wrap_id' => $temp_wrap['id'],
//                        'tax_id' => $tax_id,
//                        //材质
//                        'material' => $value['Material'],
//                        //年代
//                        'times' => $value['Times'],
//                        //断码价
//                        'cutoff_price' => $value['ShortInSizePrice'],
//                        'spec_qty' => $value['SpecCount'] ? $value['SpecCount'] : 1,
//                        'spec_name_1' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
//                        'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : '',
//                        'spec_name_3' => '发货方式',
//                        'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2]['k'] : ''
//                    );
//                    $goods_model->startTrans();
//                    $res_goods = $goods_model -> add($goods_array);
//
//
//                    if(!$res_goods){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加商品失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//                    $pic_array[] = array(
//                        'goods_id' => $res_goods,
//                        'spec_id' => 0,
//                        'store_id' => $value['StoreId'],
//                        'image_url' => $value['DefaultImg'],
//                        'type' => 1,
//                    );
//                    $pics_array = array();
//                    $first_id = '';
//
//                    foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v){
//
////                        //仓库
//                        if($v['CustomsChannelId'] && $v['storestock_id']){
//                            $res_stock = $stock_model -> where(array('storestock_id'=>$value['StoreId'].$v['CustomsChannelId'])) -> find();
//                            if(!$res_stock){
//                                $goods_model->rollback();
//                                $send_array[] = array(
//                                    'Sku' => $value['SwiftNumber'],
//                                    'Field' => 'CustomsChannelId',
//                                    'Msg' => '查询报关通道失败',
//                                    "Result" => 0
//                                );
//                                continue 2;
//                            }
//                            $res_stock = $stock_model -> where(array('storestock_id'=>$value['StoreId'].$v['CustomsChannelId'])) -> find();
//
//                            if(!$res_stock){
//                                $goods_model->rollback();
//                                $send_array[] = array(
//                                    'Sku' => $value['SwiftNumber'],
//                                    'Field' => 'CustomsChannelId',
//                                    'Msg' => '查询报关通道失败',
//                                    "Result" => 0
//                                );
//                                continue 2;
//                            }
//                        }
//
//                        //barcode
////                        if(!$v['Gtin']){
////                            $goods_model->rollback();
////                            $send_array[] = array(
////                                'Sku' => $value['SwiftNumber'],
////                                'Field' => 'Barcode',
////                                'Msg' => 'Barcode不能为空',
////                                "Result" => 0
////                            );
////                            continue 2;
////                        }
//                        $spec_array = array(
//                            'goods_id' => $res_goods,
//                            'sku' => $v['Sku'],
//                            'price' => $v['Price'],
//                            'stock' => $v['StockNum'],
//                            'spec_1' => '',
//                            'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
//                            //临时图 需要改
//                            //临时图 需要改
//                            'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
////                            'spec_3' => $res_stock['stock_name'],
////                            'spec_3value' => $value['StoreId'].$v['CustomsChannelId'],
//                            'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
//                            'tax_price' => round($consolidated_tax * $v['Price'],2),
//                            'barcode' => $v['Gtin'],
//
//                        );
//                        $res_spec = $spec_model -> add($spec_array);
//
//                        if($k == 0){
//                            $first_id = $res_spec;
//                        }
//                        if(!$res_spec){
//                            $goods_model->rollback();
//                            $send_array[] = array(
//                                'Sku' => $value['SwiftNumber'],
//                                'Field' => '',
//                                'Msg' => '添加规格失败',
//                                "Result" => 0
//                            );
//                            continue 2;
//                        }
//
//                        $pic_array[] = array(
//                            'goods_id' => $res_goods,
//                            'spec_id' => $res_spec,
//                            'store_id' => $value['StoreId'],
//                            'image_url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url'],
//                            'type' => 2,
//                        );
//
////                    $pics_array[] = array(
////                        'spec_id' => $res_spec,
////                        'url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url']
////                    );
//
//                    }
//                    foreach($_POST['ProductItems'][$key]['DetailsImgs'] as $k1 => $v1){
//                        $pic_array[] = array(
//                            'goods_id' => $res_goods,
//                            'spec_id' => 0,
//                            'store_id' => $value['StoreId'],
//                            'image_url' => $_POST['ProductItems'][$key]['DetailsImgs'][$k1]['url'],
//                            'type' => 3,
//                        );
//                    }
////                $pic_array[] = array(
////                    'goods_id'=> $res_goods,
////                    'store_id'=> $value['StoreId'],
////                    'url' => $value['DefaultImg'],
////                    'spec' =>  $pics_array
////                );
////                sync_data('http://customs.jingjing.shop/api/ecmalltest',json_encode($pic_array));
//
//                    //将第一个spec_id插入进goods表
//                    $res = $goods_model -> where(array('goods_id'=>$res_goods))->save(array('default_spec'=>$first_id));
//
//                    if($res === false){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加商品规格id失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }else{
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加商品成功',
//                            "Result" => 1
//                        );
//                    }
//                    $res_statistics = M('goods_statistics')->add(array('goods_id'=>$res_goods));
//                    if(!$res_statistics){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加商品收藏表失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//                    $file = fopen("test.txt","w+");
//                    fwrite($file,json_encode($pic_array,true));
//                    fclose($file);
//
//                    $res_upload = M('save_images')->addAll($pic_array);
//                    if(!$res_upload){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加图片失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
////                $this->download($pic_array);
//
//                    $goods_model->commit();
//                }
//            }else{
//                //edit
//
//                if($value['SpecItems'] && is_array($value['SpecItems'])){
//                    //logo
//                    $temp_logo = trim($value['Manufacturer']);
//                    if($temp_logo){
//                        $res_logo = $brand_model -> where(array('brand_name'=>$temp_logo)) -> find();
//                        if(!$res_logo){
//                            $logo_add = $brand_model -> add(array('brand_name'=>$temp_logo));
//                            if(!$logo_add){
//                                $send_array[] = array(
//                                    'Sku' => $value['SwiftNumber'],
//                                    'Field' => 'Manufacturer',
//                                    'Msg' => '品牌添加失败',
//                                    "Result" => 0
//                                );
//                                continue;
//                            }
//                        }
//                    }
//
//                    //出产地
//                    $temp_country = $country_model -> where(array('country_code'=>$value['CountryId'])) ->find();
//                    if(!$temp_country){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'CountryId',
//                            'Msg' => '出产地查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//                    //单位
//                    $temp_unit = $unit_model -> where(array('unit_code'=>$value['UnitId'])) ->find();
//                    if(!$temp_unit){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'CountryId',
//                            'Msg' => '出产地查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//                    //包装
//
//                    $temp_wrap = $wrap_model -> where(array('wrap_code'=>$value['WrapId'])) ->find();
//
//                    if(!$temp_wrap){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'WrapId',
//                            'Msg' => '包装查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//                    //税率
//                    $consolidated_tax = get_consolidated_tax($value['ConsumptionTaxRate'],$value['VATRate']);
//                    $r['add_tax'] = $value['VATRate'];
//                    $r['consumption_tax'] = $value['ConsumptionTaxRate'];
//                    $temp_tax = $tax_model -> where($r) ->find();
//
//                    if(!$temp_tax){
//                        $rx['add_tax'] = $value['VATRate'];
//                        $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
//                        $rx['consolidated_tax'] = $value['consolidated_tax'];
//                        $rx['tax_name'] = '消费税为'.$value['ConsumptionTaxRate'].'的商品';
//                        $rx['consolidated_tax'] = $consolidated_tax;
//                        $add_tax = $tax_model -> add($rx);
//                        if(!$add_tax){
//                            $send_array[] = array(
//                                'Sku' => $value['SwiftNumber'],
//                                'Field' => 'ConsumptionTaxRate',
//                                'Msg' => '税率查询失败',
//                                "Result" => 0
//                            );
//                            continue;
//                        }
//                        $tax_id = $add_tax;
//                    }else{
//                        $tax_id = $temp_tax['tax_id'];
//                        $consolidated_tax = $temp_tax['consolidated_tax'];
//                    }
//                    //店铺
//                    $resStore = $store_model -> where(array('store_id'=>$value['StoreId'])) -> find();
//                    if(!$resStore){
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => 'StoreId',
//                            'Msg' => '店铺查询失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//
//                    $pic = arraySort($_POST['ProductImgs'][$key]['SpecItems'], 'order', SORT_ASC);
//                    //分类
//                    $res_cate = M('gcategory')->where(array('cate_id'=>$value['CategoryId']))->find();
//                    if(!$res_cate){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '查询商品分类失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//                    $cate_name = $res_cate['cate_name'];
//                    $temp_cate = $res_cate;
//                    while ($temp_cate['parent_id'] != 0){
//                        $temp_cate = M('gcategory')->where(array('cate_id'=>$temp_cate['parent_id']))->find();
//                        $cate_name = $temp_cate['cate_name'] . ' ' . $cate_name;
//                    }
//                    $goods_array = array(
////                        'sku' => $value['Sku'],
//                        'goods_name' => $value['Name'],
//                        'description' => '<p></p>',
//                        'store_id' => $value['StoreId'],
//                        'price' => $value['Price'],
//                        'quantity' => $value['StockQuantity'],
//                        'market_price' => $value['OldPrice'],
//                        'brand' => $temp_logo,
//                        'if_show' => $value['Published'],
//                        'add_time' => $value['CreatedTimeStamp'],
//                        'last_update' => $value['UpdateTimeStamp'],
//                        //临时图 需要改
//                        'default_image' => $value['DefaultImg'],
//                        'country_id' => $temp_country['id'],
//                        'unit_id' => $temp_unit['id'],
//                        'wrap_id' => $temp_wrap['id'],
//                        'tax_id' => $tax_id,
//                        //材质
//                        'material' => $value['Material'],
//                        //年代
//                        'times' => $value['Times'],
//                        //断码价
//                        'cutoff_price' => $value['ShortInSizePrice'],
//                        'spec_qty' => $value['SpecCount'] ? $value['SpecCount'] : 1,
//                        'spec_name_1' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
//                        'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : '',
//                        'spec_name_3' => '发货方式',
//                        'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2]['k'] : ''
//                    );
//                    $goods_model->startTrans();
//                    $res_goods = $goods_model -> where(array('sku'=>$value['Sku']))-> save($goods_array);
//
//
//                    if($res_goods === false){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '修改商品失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//
//                    $pic_array[] = array(
//                        'goods_id' => $res_sku['goods_id'],
//                        'spec_id' => 0,
//                        'store_id' => $value['StoreId'],
//                        'image_url' => $value['DefaultImg'],
//                        'type' => 1,
//                    );
//                    $pics_array = array();
//                    $first_id = '';
//
//                    foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v){
//
////                        //仓库
////                        $res_stock = $stock_model -> where(array('storestock_id'=>$value['StoreId'].$v['CustomsChannelId'])) -> find();
////
////                        if(!$res_stock){
////                            $goods_model->rollback();
////                            $send_array[] = array(
////                                'Sku' => $value['SwiftNumber'],
////                                'Field' => 'CustomsChannelId',
////                                'Msg' => '查询报关通道失败',
////                                "Result" => 0
////                            );
////                            continue 2;
////                        }
//
//                        //barcode
////                        if(!$v['Gtin']){
////                            $goods_model->rollback();
////                            $send_array[] = array(
////                                'Sku' => $value['SwiftNumber'],
////                                'Field' => 'Barcode',
////                                'Msg' => 'Barcode不能为空',
////                                "Result" => 0
////                            );
////                            continue 2;
////                        }
//
//                        //规格是否存在
//                        $res_goods_sku = $spec_model -> where(array('sku'=>$v['Sku']))->find();
//
//                        if(!$res_goods_sku){
//                            if($res_sku){
//                                $goods_id = $res_sku['goods_id'];
//                            }else{
//                                $goods_id = $res_goods;
//                            }
//                            $spec_array = array(
//                                'goods_id' => $goods_id,
//                                'sku' => $v['Sku'],
//                                'price' => $v['Price'],
//                                'stock' => $v['StockNum'],
//                                'spec_1' => '',
//                                'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
//                                //临时图 需要改
//                                //临时图 需要改
//                                'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
////                                'spec_3' => $res_stock['stock_name'],
////                                'spec_3value' => $value['StoreId'].$v['CustomsChannelId'],
//                                'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
//                                'tax_price' => round($consolidated_tax * $v['Price'],2),
//                                'barcode' => $v['Gtin'],
//
//                            );
//                            $res_spec = $spec_model -> add($spec_array);
//                        }else{
//                            if($res_sku){
//                                $goods_id = $res_sku['goods_id'];
//                            }else{
//                                $goods_id = $res_goods;
//                            }
//                            $spec_array = array(
//                                'goods_id' => $goods_id,
//                                'price' => $v['Price'],
//                                'stock' => $v['StockNum'],
//                                'spec_1' => $_POST['ProductItems'][$key]['ProductImgs'][$k] ? $_POST['ProductItems'][$key]['ProductImgs'][$k] : '',
//                                'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
//                                //临时图 需要改
//                                //临时图 需要改
//                                'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
////                                'spec_3' => $res_stock['stock_name'],
////                                'spec_3value' => $value['StoreId'].$v['CustomsChannelId'],
//                                'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
//                                'tax_price' => round($consolidated_tax * $v['Price'],2),
//                                'barcode' => $v['Gtin'],
//
//                            );
//                            $res_spec = $spec_model -> where(array('sku'=>$v['Sku'])) -> save($spec_array);
//                            $res_spec = $spec_model -> where(array('sku'=>$v['Sku'])) ->find();
//                        }
//
//
//                        if($k == 0){
//                            if(!$res_goods_sku){
//                                $first_id = $res_spec['spec_id'];
//                            }else{
//                                $first_id = $res_goods_sku['spec_id'];
//                            }
//                        }
//
//                        if(!$res_spec){
//                            $goods_model->rollback();
//                            $send_array[] = array(
//                                'Sku' => $value['SwiftNumber'],
//                                'Field' => '',
//                                'Msg' => '添加规格失败',
//                                "Result" => 0
//                            );
//                            continue 2;
//                        }
//
//                        if(!$res_goods_sku){
//                            $spec_id = $res_spec;
//                        }else{
//                            $spec_id = $res_goods_sku['spec_id'];
//                        }
//
//                        $pic_array[] = array(
//                            'goods_id' => $res_sku['goods_id'],
//                            'spec_id' => $spec_id,
//                            'store_id' => $value['StoreId'],
//                            'image_url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url'],
//                            'type' => 2,
//                        );
//
////                    $pics_array[] = array(
////                        'spec_id' => $res_spec,
////                        'url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url']
////                    );
//
//                     }
//                    //删除 type为3的此商品图
//                    $cond_type['goods_id'] = $goods_id;
//                    $cond_type['type'] = 3;
//                    $res = M('save_images')->where($cond_type)->delete();
//                    if($res === false){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '删除原图片失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
//                    foreach($_POST['ProductItems'][$key]['DetailsImgs'] as $k1 => $v1){
//                        $pic_array[] = array(
//                            'goods_id' => $res_sku['goods_id'],
//                            'spec_id' => 0,
//                            'store_id' => $value['StoreId'],
//                            'image_url' => $_POST['ProductItems'][$key]['DetailsImgs'][$k1]['url'],
//                            'type' => 3,
//                        );
//                    }
////                $pic_array[] = array(
////                    'goods_id'=> $res_goods,
////                    'store_id'=> $value['StoreId'],
////                    'url' => $value['DefaultImg'],
////                    'spec' =>  $pics_array
////                );
////                sync_data('http://customs.jingjing.shop/api/ecmalltest',json_encode($pic_array));
//
//                    //将第一个spec_id插入进goods表
//
//                    $res = $goods_model -> where(array('goods_id'=>$res_sku['goods_id']))->save(array('default_spec'=>$first_id));
//
//                    if($res === false){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加商品规格id失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }else{
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加商品成功',
//                            "Result" => 1
//                        );
//                    }
////                    $res_statistics = M('goods_statistics')->add(array('goods_id'=>$res_goods));
////                    if(!$res_statistics){
////                        $goods_model->rollback();
////                        $send_array[] = array(
////                            'Sku' => $value['SwiftNumber'],
////                            'Field' => '',
////                            'Msg' => '添加商品收藏表失败',
////                            "Result" => 0
////                        );
////                        continue;
////                    }
//                    $file = fopen("test.txt","w+");
//                    fwrite($file,json_encode($pic_array,true));
//                    fclose($file);
//
//                    $res_upload = M('save_images')->addAll($pic_array);
//                    if(!$res_upload){
//                        $goods_model->rollback();
//                        $send_array[] = array(
//                            'Sku' => $value['SwiftNumber'],
//                            'Field' => '',
//                            'Msg' => '添加图片失败',
//                            "Result" => 0
//                        );
//                        continue;
//                    }
////                $this->download($pic_array);
//                    $goods_model->commit();
//                }
//            }
//        }
////        $url = C('ERP_URL'); #url 地址必须 http://xxxxx
////        $port = C('ERP_URL');
////        $t=1;
////        $res = _post_to_oms($url,$port,$t,'post',$send_array);
//        if(count($send_array) > 0){
//            echo json_encode($send_array,JSON_UNESCAPED_UNICODE);
//            exit;
//        }
//        $return_array = array(
//            'Success' => 1,
//            'Code' => 200,
//            'Msg' => '商品状态修改成功',
//            "Result" => 0
//        );
//        echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
//        exit;
//
//    }

    public function addGoods(){
        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('"[','[',$GLOBALS['HTTP_RAW_POST_DATA']);
        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace(']"',']',$GLOBALS['HTTP_RAW_POST_DATA']);
        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        if(!$_POST || !is_array($_POST)){
            $return_array = array(
                'MessageCode' => 2,
                'Message' => '参数错误'
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
        $goods_model = M('goods');
        $spec_model = M('goods_spec');
        $brand_model = M('brand');
        $country_model = M('country_info');
        $unit_model = M('unit');
        $wrap_model = M('wrap');
        $tax_model = M('my_tax');
        $stock_model = M('storestock');
        $store_model = M('store');

        if(!$_POST['ProductItems'] || !is_array($_POST['ProductItems'])){
            $return_array = array(
                'Sku' => '',
                'Field' => 'Manufacturer',
                'Msg' => '参数错误',
                "Result" => 0
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
        $send_array = array();
        $pic_array = array();

        foreach ($_POST['ProductItems'] as $key => $value) {
//            try{
            if ($value['SpecItems'] && is_array($value['SpecItems'])) {
                //logo
                $temp_logo = trim($value['Manufacturer']);
                if ($temp_logo) {
                    $res_logo = $brand_model->where(array('brand_name' => $temp_logo))->find();
                    if (!$res_logo) {
                        $logo_add = $brand_model->add(array('brand_name' => $temp_logo));
                        if (!$logo_add) {
                            $send_array[] = array(
                                'Sku' => $value['SwiftNumber'],
                                'Field' => 'Manufacturer',
                                'Msg' => '品牌添加失败',
                                "Result" => 0
                            );
                            continue;
                        }
                    }
                }

                //出产地
                $temp_country = $country_model->where(array('country_code' => $value['CountryId']))->find();
                if (!$temp_country) {
                    $send_array[] = array(
                        'Sku' => $value['SwiftNumber'],
                        'Field' => 'CountryId',
                        'Msg' => '出产地查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                //单位
                $temp_unit = $unit_model->where(array('unit_code' => $value['UnitId']))->find();
                if (!$temp_unit) {
                    $send_array[] = array(
                        'Sku' => $value['SwiftNumber'],
                        'Field' => 'CountryId',
                        'Msg' => '出产地查询失败',
                        "Result" => 0
                    );
                    continue;
                }

                //包装

                $temp_wrap = $wrap_model->where(array('wrap_code' => $value['WrapId']))->find();

                if (!$temp_wrap) {
                    $send_array[] = array(
                        'Sku' => $value['SwiftNumber'],
                        'Field' => 'WrapId',
                        'Msg' => '包装查询失败',
                        "Result" => 0
                    );
                    continue;
                }

                //税率
                $consolidated_tax = get_consolidated_tax($value['ConsumptionTaxRate'], $value['VATRate']);
                $r['add_tax'] = $value['VATRate'];
                $r['consumption_tax'] = $value['ConsumptionTaxRate'];
                $temp_tax = $tax_model->where($r)->find();

                if (!$temp_tax) {
                    $rx['add_tax'] = $value['VATRate'];
                    $rx['consumption_tax'] = $value['ConsumptionTaxRate'];
                    $rx['consolidated_tax'] = $value['consolidated_tax'];
                    $rx['tax_name'] = '消费税为' . $value['ConsumptionTaxRate'] . '的商品';
                    $rx['consolidated_tax'] = $consolidated_tax;
                    $add_tax = $tax_model->add($rx);
                    if (!$add_tax) {
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => 'ConsumptionTaxRate',
                            'Msg' => '税率查询失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $tax_id = $add_tax;
                } else {
                    $tax_id = $temp_tax['tax_id'];
                    $consolidated_tax = $temp_tax['consolidated_tax'];
                }
                //店铺
                $resStore = $store_model->where(array('store_id' => $value['StoreId']))->find();
                if (!$resStore) {
                    $send_array[] = array(
                        'Sku' => $value['SwiftNumber'],
                        'Field' => 'StoreId',
                        'Msg' => '店铺查询失败',
                        "Result" => 0
                    );
                    continue;
                }
                $pic = arraySort($_POST['ProductItems'][$key]['ProductImgs'], 'order', SORT_ASC);
                //分类
                $res_cate = M('gcategory')->where(array('cate_id' => $value['CategoryId']))->find();
                if (!$res_cate) {
                    $goods_model->rollback();
                    $send_array[] = array(
                        'Sku' => $value['SwiftNumber'],
                        'Field' => '',
                        'Msg' => '查询商品分类失败',
                        "Result" => 0
                    );
                    continue;
                }
                $cate_name = $res_cate['cate_name'];
                $temp_cate = $res_cate;
                while ($temp_cate['parent_id'] != 0) {
                    $temp_cate = M('gcategory')->where(array('cate_id' => $temp_cate['parent_id']))->find();
                    $cate_name = $temp_cate['cate_name'] . ' ' . $cate_name;
                }
                if($value['Gender'] == '10'){
                    $sex = '男';
                }else if($value['Gender'] == '20'){
                    $sex = '女';
                }else if($value['Gender'] == '30'){
                    $sex = '儿童';
                }else if($value['Gender'] == '40'){
                    $sex = '中性';
                }else{
                    $sex = '';
                }
//                switch ($value['Gender'])
//                {
//                    case 10:
//                        $sex = '男';
//                        break;
//                    case 20:
//                        $sex = '女';
//                        break;
//                    case 30:
//                        $sex = '儿童';
//                        break;
//                    case 40:
//                        $sex = '中性';
//                        break;
//                    default:
//                        $sex = '';
//                }
                $goods_array = array(
                    'sku' => $value['Sku'],
                    'cate_id' => $value['CategoryId'],
                    'cate_name' => $cate_name,
                    'goods_name' => $value['Name'],
                    'description' => '<p></p>',
                    'store_id' => $value['StoreId'],
                    'price' => $value['Price'],
                    'quantity' => $value['StockQuantity'],
                    'market_price' => $value['OldPrice'],
                    'brand' => $temp_logo,
                    'if_show' => $value['Published'],
                    'closed' => 1,
                    'add_time' => $value['CreatedTimeStamp'],
                    'last_update' => $value['UpdateTimeStamp'],
                    //临时图 需要改
                    'default_image' => $value['DefaultImg'],
                    'country_id' => $temp_country['id'],
                    'unit_id' => $temp_unit['id'],
                    'wrap_id' => $temp_wrap['id'],
                    'tax_id' => $tax_id,
                    //材质
                    'material' => $value['Material'],
                    //年代
                    'times' => $value['Times'],
                    //断码价
                    'cutoff_price' => $value['ShortInSizePrice'],
                    'sex' => $sex,
                    'international_code' => $value['InternationalCode'],
                    'spec_qty' => $value['SpecCount'] ? $value['SpecCount'] : 1,
                    'spec_name_1' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][0]['k'] : '',
                    'spec_name_2' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][1]['k'] : '',
                    'spec_name_3' => '发货方式',
                    'swift_number' => $value['SwiftNumber'],
                    'screen_label' => $value['ShortDescription']
//                        'spec_name_4' => $value['SpecCount'] && $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2] ? $_POST['ProductItems'][$key]['SpecItems'][0]['AttrComb'][2]['k'] : ''
                );

                $goods_model->startTrans();
                //查重
                $res_sku = $goods_model->where(array('sku' => $value['Sku']))->find();
                if (!$res_sku) {
                    $res_goods = $goods_model->add($goods_array);


                    if (!$res_goods) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加商品失败',
                            "Result" => 0
                        );
                        continue;
                    }

                    $pic_array[] = array(
                        'goods_id' => $res_goods,
                        'spec_id' => 0,
                        'store_id' => $value['StoreId'],
                        'image_url' => $value['DefaultImg'],
                        'type' => 1,
                    );
                    $pics_array = array();
                    $first_id = '';
                    foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v) {

//                        //仓库
                        if ($v['CustomsChannelId'] && $v['storestock_id']) {
                            $res_stock = $stock_model->where(array('storestock_id' => $value['StoreId'] . $v['CustomsChannelId']))->find();
                            if (!$res_stock) {
                                $goods_model->rollback();
                                $send_array[] = array(
                                    'Sku' => $value['SwiftNumber'],
                                    'Field' => 'CustomsChannelId',
                                    'Msg' => '查询报关通道失败',
                                    "Result" => 0
                                );
                                continue 2;
                            }
                            $res_stock = $stock_model->where(array('storestock_id' => $value['StoreId'] . $v['CustomsChannelId']))->find();

                            if (!$res_stock) {
                                $goods_model->rollback();
                                $send_array[] = array(
                                    'Sku' => $value['SwiftNumber'],
                                    'Field' => 'CustomsChannelId',
                                    'Msg' => '查询报关通道失败',
                                    "Result" => 0
                                );
                                continue 2;
                            }
                        }
                        $spec_array = array(
                            'goods_id' => $res_goods,
                            'sku' => $v['Sku'],
                            'price' => $v['Price'],
                            'stock' => 0,
                            'spec_1' => '',
                            'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
                            //临时图 需要改
                            //临时图 需要改
                            'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] || strlen($_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v']) ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
//                            'spec_3' => $res_stock['stock_name'],
//                            'spec_3value' => $value['StoreId'].$v['CustomsChannelId'],
//                                'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
                            'tax_price' => round($consolidated_tax * $v['Price'], 2),
                            'barcode' => $v['Gtin'],
                            'international_code' => $v['InternationalCode']

                        );
                        $res_spec = $spec_model->add($spec_array);

                        if ($k == 0) {
                            $first_id = $res_spec;
                        }
                        if (!$res_spec) {
                            $goods_model->rollback();
                            $send_array[] = array(
                                'Sku' => $value['SwiftNumber'],
                                'Field' => '',
                                'Msg' => '添加规格失败',
                                "Result" => 0
                            );
                            continue 2;
                        }

                        $pic_array[] = array(
                            'goods_id' => $res_goods,
                            'spec_id' => $res_spec,
                            'store_id' => $value['StoreId'],
                            'image_url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url'],
                            'type' => 2,
                        );

                    }
                    foreach ($_POST['ProductItems'][$key]['DetailsImgs'] as $k1 => $v1) {
                        $pic_array[] = array(
                            'goods_id' => $res_goods,
                            'spec_id' => 0,
                            'store_id' => $value['StoreId'],
                            'image_url' => $_POST['ProductItems'][$key]['DetailsImgs'][$k1]['url'],
                            'type' => 3,
                        );
                    }
                    //将第一个spec_id插入进goods表
                    $res = $goods_model->where(array('goods_id' => $res_goods))->save(array('default_spec' => $first_id));

                    if ($res === false) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加商品规格id失败',
                            "Result" => 0
                        );
                        continue;
                    } else {
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加商品成功',
                            "Result" => 3
//                            "Result" => 1
                        );
                    }
                    $res_statistics = M('goods_statistics')->add(array('goods_id' => $res_goods));
                    if (!$res_statistics) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加商品收藏表失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $file = fopen("test.txt", "w+");
                    fwrite($file, json_encode($pic_array, true));
                    fclose($file);

                    $res_upload = M('save_images')->addAll($pic_array);
                    if (!$res_upload) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加图片失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $goods_model->commit();
                } else {

                    $res_goods = $goods_model->where(array('sku' => $value['Sku']))->save($goods_array);


                    if ($res_goods === false) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '修改商品失败',
                            "Result" => 0
                        );
                        continue;
                    }

                    $pic_array[] = array(
                        'goods_id' => $res_sku['goods_id'],
                        'spec_id' => 0,
                        'store_id' => $value['StoreId'],
                        'image_url' => $value['DefaultImg'],
                        'type' => 1,
                    );
                    $pics_array = array();
                    $first_id = '';
                    foreach ($_POST['ProductItems'][$key]['SpecItems'] as $k => $v) {
                        //规格是否存在
                        $res_goods_sku = $spec_model->where(array('sku' => $v['Sku']))->find();

                        if (!$res_goods_sku) {
                            if ($res_sku) {
                                $goods_id = $res_sku['goods_id'];
                            } else {
                                $goods_id = $res_goods;
                            }
                            $spec_array = array(
                                'goods_id' => $goods_id,
                                'sku' => $v['Sku'],
                                'price' => $v['Price'],
                                'stock' => 0,
                                'spec_1' => '',
                                'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
                                //临时图 需要改
                                //临时图 需要改
                                'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] || strlen($_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v']) ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
//                                'spec_3' => $res_stock['stock_name'],
//                                'spec_3value' => $value['StoreId'].$v['CustomsChannelId'],
//                                    'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
                                'tax_price' => round($consolidated_tax * $v['Price'], 2),
                                'barcode' => $v['Gtin'],
                                'international_code' => $v['InternationalCode']

                            );
                            $res_spec = $spec_model->add($spec_array);
                        } else {
                            if ($res_sku) {
                                $goods_id = $res_sku['goods_id'];
                            } else {
                                $goods_id = $res_goods;
                            }
                            $spec_array = array(
                                'goods_id' => $goods_id,
                                'price' => $v['Price'],
                                'stock' => 0,
                                'spec_1' => $_POST['ProductItems'][$key]['ProductImgs'][$k] ? $_POST['ProductItems'][$key]['ProductImgs'][$k] : '',
                                'spec_1value' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][0]['v'] : '',
                                //临时图 需要改
                                //临时图 需要改
                                'spec_2' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] || strlen($_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v']) ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][1]['v'] : '',
//                                'spec_3' => $res_stock['stock_name'],
//                                'spec_3value' => $value['StoreId'].$v['CustomsChannelId'],
//                                    'spec_4' => $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] ? $_POST['ProductItems'][$key]['SpecItems'][$k]['AttrComb'][2]['v'] : '',
                                'tax_price' => round($consolidated_tax * $v['Price'], 2),
                                'barcode' => $v['Gtin'],
                                'international_code' => $v['InternationalCode']

                            );
                            $res_spec = $spec_model->where(array('sku' => $v['Sku']))->save($spec_array);
                            $res_spec = $spec_model->where(array('sku' => $v['Sku']))->find();
                        }


                        if ($k == 0) {
                            if (!$res_goods_sku) {
                                $first_id = $res_spec['spec_id'];
                            } else {
                                $first_id = $res_goods_sku['spec_id'];
                            }
                        }

                        if (!$res_spec) {
                            $goods_model->rollback();
                            $send_array[] = array(
                                'Sku' => $value['SwiftNumber'],
                                'Field' => '',
                                'Msg' => '添加规格失败',
                                "Result" => 0
                            );
                            continue 2;
                        }

                        if (!$res_goods_sku) {
                            $spec_id = $res_spec;
                        } else {
                            $spec_id = $res_goods_sku['spec_id'];
                        }

                        $pic_array[] = array(
                            'goods_id' => $res_sku['goods_id'],
                            'spec_id' => $spec_id,
                            'store_id' => $value['StoreId'],
                            'image_url' => $_POST['ProductItems'][$key]['ProductImgs'][$k]['url'],
                            'type' => 2,
                        );
                    }
                    //删除 type为3的此商品图
                    //删除type所有的主图
                    $cond_type['goods_id'] = $goods_id;
//                    $cond_type['type'] = 3;
                    $res = M('save_images')->where($cond_type)->delete();
                    if ($res === false) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '删除原图片失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    foreach ($_POST['ProductItems'][$key]['DetailsImgs'] as $k1 => $v1) {
                        $pic_array[] = array(
                            'goods_id' => $res_sku['goods_id'],
                            'spec_id' => 0,
                            'store_id' => $value['StoreId'],
                            'image_url' => $_POST['ProductItems'][$key]['DetailsImgs'][$k1]['url'],
                            'type' => 3,
                        );
                    }
                    //将第一个spec_id插入进goods表
                    $res = $goods_model->where(array('goods_id' => $res_sku['goods_id']))->save(array('default_spec' => $first_id));

                    if ($res === false) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加商品规格id失败',
                            "Result" => 0
                        );
                        continue;
                    } else {
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加商品成功',
                            "Result" => 3
//                            "Result" => 1
                        );
                    }
                    $file = fopen("test.txt", "w+");
                    fwrite($file, json_encode($pic_array, true));
                    fclose($file);

                    $res_upload = M('save_images')->addAll($pic_array);
                    if (!$res_upload) {
                        $goods_model->rollback();
                        $send_array[] = array(
                            'Sku' => $value['SwiftNumber'],
                            'Field' => '',
                            'Msg' => '添加图片失败',
                            "Result" => 0
                        );
                        continue;
                    }
                    $goods_model->commit();
                }
            }
        }
                if(count($send_array) > 0){
                    echo json_encode($send_array,JSON_UNESCAPED_UNICODE);
                    exit;
                }
                $return_array = array(
                    'Success' => 1,
                    'Code' => 200,
                    'Msg' => '商品状态修改成功',
                    "Result" => 1
                );
                echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
                exit;
//            }catch(\Exception $e){
                $send_array[] = array(
                    'Sku' => $value['SwiftNumber'],
                    'Field' => 'CountryId',
                    'Msg' => '网络错误',
                    "Result" => 0
                );
                echo json_encode($send_array,JSON_UNESCAPED_UNICODE);
                exit;
//            }
    }

    public function addCategory(){


        //test

        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);

//        {"Id":"148","Name":"中裙","ParentId":"122"}
        if(!$_POST || !$_POST['Id']){
            $return_array = array(
                'MessageCode' => '2',
                'Method' => 'addCategory',
                'ErrorMsg' => '参数错误',
            );
            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
            exit;
        }
        $data = array(
            'cate_id' => $_POST['Id'],
            'cate_name' => $_POST['Name'],
            'parent_id' => $_POST['ParentId'],

        );
        $res_select = M('gcategory')->where(array('cate_id'=>$_POST['Id']))->find();
        if($res_select){
            $res = M('gcategory')->where(array('cate_id'=>$_POST['Id']))->save($data);
            if($res === false){
                $return_array = array(
                    'MessageCode' => '2',
                    'Method' => 'addCategory',
                    'ErrorMsg' => '修改失败',
                );
                echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
                exit;
            }
            //改商品
            if($_POST['ParentId'] != 0){
                $res_goods = M('goods')->where(array('cate_id'=>$_POST['Id']))->select();
                foreach ($res_goods as $k => $v){
                    //1所有
                    $str = preg_replace("/(.*)(\s+)(.*)/i","$1$2".$_POST['Name'], $v['cate_name']);
                    $cate = array(
                        'cate_name' => $str
                    );
                    $res = M('goods')->where(array('goods_id'=>$v['goods_id']))->save($cate);
                    if ($res === false){
                        $return_array = array(
                            'MessageCode' => '2',
                            'Method' => 'addCategory',
                            'ErrorMsg' => '商品表分类修改失败',
                        );
                        echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
                        exit;
                    }
                }
            }else{
                $res_goods = M('goods')->join('left join ecm_gcategory on ecm_goods.cate_id = ecm_gcategory.cate_id')->where(array('ecm_gcategory.parent_id'=>$_POST['Id']))->select();
                foreach ($res_goods as $k => $v){
                    $data_goods = objcet(array());
                    $data_goods['cate_name'] = preg_replace("/(.*)(\s+)(.*)/iU",$_POST['Name']."$2$3",$data_goods['cate_name']);
                    $res = M('goods')->where(array('goods_id'=>$v['goods_id']))->save($data_goods);
                    if ($res === false){
                        $return_array = array(
                            'MessageCode' => '2',
                            'Method' => 'addCategory',
                            'ErrorMsg' => '商品表一级分类修改失败',
                        );
                        echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
                        exit;
                    }
                }
            }

        }else{
            $res = M('gcategory')->add($data);
            if(!$res){
                $return_array = array(
                    'MessageCode' => '2',
                    'Method' => 'addCategory',
                    'ErrorMsg' => '添加失败',
                );
                echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
                exit;
            }
        }

        $return_array = array(
            'MessageCode' => '1',
            'Method' => 'addCategory',
            'ErrorMsg' => '添加成功',
        );
        echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
        exit;
    }

    public function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }



//    public function download()
    public function download($data)
    {


        $send_data = array();
//        $data = array(
//            0 => array(
//                'goods_id'=> 109,
//                'store_id'=> 2,
//                'url' => 'http://pic3.nipic.com/20090514/2639204_233912087_2.jpg',
//                'spec' => array(
//                    0 =>array(
//                        'spec_id' => '127',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    1 =>array(
//                        'spec_id' => '128',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    2 =>array(
//                        'spec_id' => '129',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    3 =>array(
//                        'spec_id' => '130',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    ),
//                    4 =>array(
//                        'spec_id' => '131',
//                        'url' => 'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg'
//                    )
//
//                )
//            )
//        );

//        $images = array( 'http://pic3.nipic.com/20090514/2639204_233912087_2.jpg',
//            'http://pic1a.nipic.com/2008-10-22/20081022103550586_2.jpg');
        foreach ( $data as $k => $v ) {

            if(strpos(__ROOT__,'ecmall')){
                $path = $_SERVER['DOCUMENT_ROOT'].'/ecmall/data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/';
            }else{
                $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/';
            }

            $file_name = downloadImage($v['url'],$path,1);

            $thumb_path = './../data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/'.$file_name;

            $save_path = './../data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/small_'.$file_name;


            make_thumb($thumb_path,$save_path);

            //取data后面

            $path_arr = explode('data',$path);
//            $path_str = 'data'.$path_arr[1];
            $path_str = 'data'.$path_arr[2];

            $thumb_arr = explode('data',$save_path);
//            $thumb_str = 'data'.$thumb_arr[1];
            $thumb_str = 'data'.$path_arr[2];

            $send_data[$k]['goods_id'] = $v['goods_id'];
            $send_data[$k]['store_id'] = $v['store_id'];
            $send_data[$k]['file_name'] = $file_name;
            $send_data[$k]['file_path'] = $path_str.$file_name;
            $send_data[$k]['thumb_name'] = 'small_'.$file_name;
            $send_data[$k]['thumb_path'] = $thumb_str.$file_name;
            $send_data[$k]['spec'] = array();
            foreach ($data[$k]['spec'] as $key => $value){
                if(strpos(__ROOT__,'ecmall')){
                    $path = $_SERVER['DOCUMENT_ROOT'].'/ecmall/data/files/store_'.$v['store_id'].'/goodsspec/';
                }else{
                    $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'/goodsspec/';
                }
                $file_spec_name = downloadImage($value['url'],$path,2);


                //取data后面

                $path_arr = explode('data',$path);
//                $path_str = 'data'.$path_arr[1];
                $path_str = 'data'.$path_arr[2];

                $send_data[$k]['spec'][$key] = array();
                $send_data[$k]['spec'][$key]['spec_id'] = $value['spec_id'];
                $send_data[$k]['spec'][$key]['file_name'] = $file_spec_name;
                $send_data[$k]['spec'][$key]['file_path'] = $path_str.$file_spec_name;
            }
        }
        save_sql($send_data);
    }

    public function closeGoods(){
//        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('"[','[',$GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace(']"',']',$GLOBALS['HTTP_RAW_POST_DATA']);
//        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        $_POST = json_decode(file_get_contents('php://input'), true);
        if(!$_POST['Sku']){
            $return_array[] = array(
                'Sku' => '',
                'Method' => 'closeGoods',
                'Msg' => '参数错误',
                "Result" => 2
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
        try{
            $ex = explode(',',$_POST['Sku']);
            foreach ($ex as $k => $v){
                $res = M('goods')->where(array('sku'=>$v))->find();
                if(!$res){
                    $return_array[] = array(
                        'Result' => '2',
                        'Method' => 'closeGoods',
                        'Msg' => '商品不存在',
                        'Sku' => $v
                    );
                    continue;
                }
                $res = M('goods')->where(array('sku'=>$v))->save(array('closed'=>1));
                if($res === false){
                    $return_array[] = array(
                        'Result' => '2',
                        'Method' => 'closeGoods',
                        'Msg' => '下架失败',
                        'Sku' => $v
                    );
                    continue;
                }
                $return_array[] = array(
                    'Result' => '1',
                    'Method' => 'closeGoods',
                    'Msg' => '下架成功',
                    'Sku' => $v
                );
            }
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;

        }catch(Exception $e){
            $return_array[] = array(
                'Result' => '2',
                'Method' => 'closeGoods',
                'Msg' => '网络错误',
                'Sku' => ''
            );
            echo json_encode($return_array,JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

}

/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys   要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC) {
    $keysValue = array();
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}
function random_filename()
{
    $seedstr = explode(" ", microtime(), 5);
    $seed    = $seedstr[0] * 10000;
    srand($seed);
    $random  = rand(1000,10000);

    return date("YmdHis", time()) . $random;
}


//计算综合税
function get_consolidated_tax($consumption_tax = 0,$add_tax = 0.13){
    return round((($consumption_tax + $add_tax) / (1 - $consumption_tax)) * 0.7,3);
}

//下载远程图片

function downloadImage($url,$path,$type)
{
    $ch = curl_init(); //curl_init(): 初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。

    curl_setopt($ch, CURLOPT_URL, $url);//curl_setopt(): 设置一个cURL传输选项,

//CURLOPT_URL: 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //CURLOPT_RETURNTRANSFER: TRUE将curl_exec()获取的信息以字符串返回，而不是直接输出。

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//CURLOPT_CONNECTTIMEOUT: 在尝试连接时等待的秒数。设置为0，则无限等待。

    $file = curl_exec($ch);//curl_exec(): 执行一个cURL会话

    curl_close($ch);//curl_close(): 关闭一个cURL会话



    $rs = mkdirs_1($path);

    $res = saveAsImage($url, $file, $path, $type);
    return $res;
}

//type
// 1:商品主图

// 2:商品规格图

function saveAsImage($url, $file, $path ,$type = 1)
{


    $filenames = pathinfo($url, PATHINFO_BASENAME);//pathinfo(): 返回文件路径的信息

    $str=explode('.',$filenames);

    if($type == 1){
        $filename = date("YmdHis".(time() % 200))+rand(100000,999999).'.'.$str[1];
    }else if($type == 2){
//        $filename = 'spec_'.date("YmdHis".(time() % 200)).'.'.$str[1];
        $filename = date("YmdHis".(time() % 200))+rand(100000,999999).'.'.$str[1];

    }


    $resource = fopen($path.$filename, 'a');//fopen(): 打开文件或url

    $rs = fwrite($resource, $file);//fwrite(): 写入文件

//    $ming = date("YmdHis".(time() % 200));

    fclose($resource);//fclose(): 关闭一个已经打开的文件指针
    if($type == 2){
        $filename1 = 'spec_'.date("YmdHis".(time() % 200)).'.'.$str[1];
        $resource = fopen($path.$filename1, 'a');//fopen(): 打开文件或url

        $rs = fwrite($resource, $file);//fwrite(): 写入文件

//    $ming = date("YmdHis".(time() % 200));

        fclose($resource);//fclose(): 关闭一个已经打开的文件指针
    }
    return $filename;
}

function mkdirs_1($path, $mode = 0777){
    if(is_dir($path)){
        return '无法创建,已经是目录了';
    }else{
        if(mkdir($path, $mode, true)) {
            return '创建成功';
        }else{
            return '创建失败';
        }
    }
}

//制作缩略图
function make_thumb($thumb_path,$save_path){
    $image = new \Think\Image();
    $image->open($thumb_path);
    $image->thumb(300, 300,\Think\Image::IMAGE_THUMB_FIXED)->save($save_path);
}

//存数据库(4张表)
function save_sql($data){
    $file_model = M('uploaded_file');
    $goods_image_model = M('goods_image');
    $goods_model = M('goods');
    $goods_spec_model = M('goods_spec');
    foreach ($data as $k => $v){
        $data_file = array(
            'store_id'=>$v['store_id'],
            'file_type'=>'image/jpeg',
            'file_name'=>$v['file_name'],
            'file_path'=>$v['file_path'],
            'add_time'=> time(),
            'belong'=>2,
            'item_id'=>$v['goods_id']
        );
        $res = $file_model->add($data_file);
        if(!$res){
            return false;
        }

        $data_image = array(
            'goods_id'=>$v['goods_id'],
            'image_url'=>$v['file_path'],
            'thumbnail'=>$v['thumb_path'],
            'file_id'=>$res
        );
        $res = $goods_image_model->add($data_image);
        if(!$res){
            return false; 
        }

        $data_goods = array(
            'default_image'=>$v['file_path'],
        );
        $res = $goods_model->where(array('goods_id'=>$v['goods_id']))->save($data_goods);
        if(!$res){
            return false;
        }

        foreach($data[$k]['spec'] as $key => $value){
            $data_goods_spec = array(
                'spec_1'=>$value['file_path'],
            );

            $res = $goods_spec_model->where(array('spec_id'=>$value['spec_id']))->save($data_goods_spec);

            if(!$res){
                return false;
            }
        }


    }
}

function _array_column($array=array(), $column_key, $index_key=null){
    $result = array();
    foreach($array as $arr) {
        if(!is_array($arr)) continue;

        if(is_null($column_key)){
            $value = $arr;
        }else{
            $value = $arr[$column_key];
        }

        if(!is_null($index_key)){
            $key = $arr[$index_key];
            $result[$key] = $value;
        }else{
            $result[] = $value;
        }
    }
    return $result;
}

function sync_data($url, $data_string) {
    $data_string = json_encode($data_string);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    $res = curl_exec($ch);
    if(!$res){
        return array('MessageCode'=>2, 'ErrorMsg'=>'同步失败');
    }else{
        return json_decode($res,true);
    }
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $return_content = ob_get_contents();
    ob_end_clean();

    return array('code'=>$return_code, 'result'=>$return_content);
}
